import json
import time
import webapp2

from webapp2_extras.i18n import gettext as _

from apnetmodels.apnetusers import APNETUser
from apnetmodels.basicmodels import immeuble, syndicForUser
from google.appengine.api import users

from wtforms.ext.appengine.db import model_form

from common import functions

from BaseHandler import BaseHandler

class Users(BaseHandler):
    def __init__(self, *args, **kwargs):
        super(Users, self).__init__(*args, **kwargs)
        self.au = functions.GetAPNETUser()
        if not self.au:
            self.redirect(users.create_login_url(self.request.uri))
            return
        self.fields = {
                       'first_name': _('First name'), 'last_name': _('Last name'), 'primary_phone': _('Phone number'),
                       'primary_email': _('Google account primary email'), 'state': _('State'), 'created': _('Date created'),
                       'is_syndic_creator': _("Create syndic's?"), 'is_syndic_admin': _('Syndic manager?'),
                       'is_immeuble_admin': _('Immeuble manager?'), 'is_lot_owner': _('Lot owner?'),
                       'lang': _('Interface language'), 'last_active_immeuble_id': _('Last active immeuble id')}
        
    def get(self, *args, **kwargs):
        self.get_method(self.__class__, *args, **kwargs)

    def post(self, *args, **kwargs):
        self.get_method(self.__class__, *args, **kwargs)
    
    def op_list(self, *args, **kwargs):
        if not self.au.is_syndic_creator == True:
            self.redirect(users.create_login_url(self.request.uri))
            return
        imm_id = kwargs.get('imm_id', -1)
        imm = immeuble.get_by_id(int(imm_id))
        syn = imm.syndic
        
        template_values = {
                           'title': _('Users. %s' % syn.name),
                           'header': _('ATENET. Users. %s' % syn.name),
                           'app_user': self.au,
                           'immeuble': imm,
                           'lurl': users.create_logout_url('/'),
                           'section': 'syndic',
                           'leftmenu': 'users',
                           'fields': self.fields
        }

        template = self.jinja2.get_template('templates/users_list.html')
        self.response.out.write(template.render(template_values))
    
    def op_list_json(self, *args, **kwargs):
        if not self.au.is_syndic_creator == True:
            self.redirect(users.create_login_url(self.request.uri))
            return
        imm_id = kwargs.get('imm_id', -1)
        imm = immeuble.get_by_id(int(imm_id))
        
        syn = imm.syndic
        query = syndicForUser.all().filter('syndic =', syn)
        us = []
        for u in query:
            us.append([u.user.primary_email, unicode(u.user.first_name), unicode(u.user.last_name), u.user.primary_phone, functions.TrueFalseToYesNoFormat(u.user.is_syndic_creator), functions.TrueFalseToYesNoFormat(u.user.is_syndic_admin), functions.TrueFalseToYesNoFormat(u.user.is_immeuble_admin), functions.TrueFalseToYesNoFormat(u.user.is_lot_owner), functions.userstateformat(u.user.state), str(u.user.key())])
        ret = {}
        ret['aaData'] = us
        self.response.out.write(json.dumps(ret))
    
    def op_add(self, *args, **kwargs):
        imm_id = kwargs.get('imm_id', -1)
        imm = immeuble.get_by_id(int(imm_id))
        syn = imm.syndic
        
        ok_message = ''
        APNETUserForm = model_form(APNETUser, exclude=['state','last_active_immeuble_id'])
        
        if self.request.method == 'GET':
            form = APNETUserForm()
            
        if self.request.method == 'POST':
            form = APNETUserForm(self.request.POST)
            if form.validate():
                pk_email = form['primary_email'].data.strip()
                au1 = APNETUser(first_name='fn', last_name='ln', primary_phone='1', key_name = pk_email)
                form.populate_obj(au1)
                au1.put()
                form = APNETUserForm()
                while not au1.is_saved():
                    time.sleep(2)
                
                au2 = syndicForUser(syndic=syn, user=au1)
                au2.put()
                while not au2.is_saved():
                    time.sleep(2)
                ok_message = _('User was added.')
        
        template_values = {'form': form, 'ok_message': ok_message, 'fields': self.fields}
        
        template = self.jinja2.get_template('templates/base_form.html')
        self.response.out.write(template.render(template_values))
    
    def op_edit(self, *args, **kwargs):
        imm_id = kwargs.get('imm_id', -1)
        u_id = kwargs.get('u_id', -1)
        imm = immeuble.get_by_id(int(imm_id))
        if not imm:
            self.redirect(webapp2.uri_for('mainpage'))
            return
        au1 = APNETUser.get(u_id)
        
        ok_message = ''
        APNETUserForm = model_form(APNETUser, exclude=['last_active_immeuble_id'])
        
        if self.request.method == 'GET':
            form = APNETUserForm(obj=au1)
            
        if self.request.method == 'POST':
            form = APNETUserForm(self.request.POST)
            if form.validate():
                form.populate_obj(au1)
                au1.put()
                
                ok_message = _('User was updated.')
        
        template_values = {'form': form, 'ok_message': ok_message, 'fields': self.fields}
        
        template = self.jinja2.get_template('templates/base_form.html')
        self.response.out.write(template.render(template_values))
    
    def op_set_lang(self, *args, **kwargs):
        au1 = APNETUser.get(self.au.key())
        APNETUserForm = model_form(APNETUser, only=['lang'])
        
        form = APNETUserForm(obj=au1)
        if self.request.method == 'POST':
            form = APNETUserForm(self.request.POST)
            if form.validate():
                form.populate_obj(au1)
                au1.put()
        
        self.redirect(self.request.referer)
    
    def op_profile(self, *args, **kwargs):
        imm_id = kwargs.get('imm_id', -1)
        imm = immeuble.get_by_id(int(imm_id))
        au = self.au
        ok_message = ''
        APNETUserForm = model_form(APNETUser, exclude=['state', 'last_active_immeuble_id'])
        
        if self.request.method == 'GET':
            form = APNETUserForm(obj=self.au)
        
        if self.request.method == 'POST':
            form = APNETUserForm(self.request.POST)
            if form.validate():
                form.populate_obj(au)
                au.put()
                ok_message = _('Your profile was updated.')
        
        template_values = {
                           'title': _('Profile'),
                           'header': _('ATENET. My profile'),
                           'legend': _('My details'),
                           'immeuble': imm,
                           'main_content': form,
                           'app_user': self.au,
                           'ok_message': ok_message,
                           'fields': self.fields,
                           'lurl': users.create_logout_url('/')
                           }
    
        template = self.jinja2.get_template('templates/user.html')
        self.response.out.write(template.render(template_values))
